<template>
  <div class="order-list-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-section">
      <el-breadcrumb :separator-icon="ArrowRight">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/user/profile' }">个人中心</el-breadcrumb-item>
        <el-breadcrumb-item>我的订单</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">我的订单</h1>
      <div class="page-subtitle">查看和管理您的所有订单</div>
    </div>
    
    <!-- 订单状态筛选 -->
    <div class="order-status-filter">
      <div 
        v-for="status in orderStatuses" 
        :key="status.value"
        class="status-item"
        :class="{ active: currentStatus === status.value }"
        @click="handleStatusChange(status.value)"
      >
        <span class="status-icon">
          <i :class="status.icon"></i>
        </span>
        <span class="status-text">{{ status.label }}</span>
        <span v-if="status.count > 0" class="status-count">{{ status.count }}</span>
      </div>
    </div>
    
    <!-- 订单列表内容 -->
    <div v-if="!loading" class="order-list-content">
      <!-- 订单为空 -->
      <div v-if="orders.length === 0" class="empty-orders">
        <div class="empty-icon">
          <el-icon><Ticket /></el-icon>
        </div>
        <div class="empty-text">暂无订单记录</div>
        <el-button type="primary" @click="goShopping" class="go-shopping-btn">
          去购物
        </el-button>
      </div>
      
      <!-- 订单列表 -->
      <div v-else class="orders-list">
        <OrderItem 
          v-for="order in orders" 
          :key="order.id"
          :order="order"
          @view-detail="handleViewDetail"
          @cancel-order="handleCancelOrder"
          @confirm-receipt="handleConfirmReceipt"
          @pay-order="handlePayOrder"
          @delete-order="handleDeleteOrder"
        />
      </div>
      
      <!-- 分页 -->
      <div v-if="orders.length > 0" class="pagination-section">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalOrders"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div v-else class="loading-container">
      <el-loading v-loading="loading" element-loading-text="加载中..." />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useOrderStore } from '../../store/modules/order'
import { useUserStore } from '../../store/modules/user'
import { ArrowRight, Ticket } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import OrderItem from '../../components/order/OrderItem.vue'

const router = useRouter()
const orderStore = useOrderStore()
const userStore = useUserStore()

// 响应式数据
const loading = ref(true)
const orders = ref([])
const currentStatus = ref('all')
const currentPage = ref(1)
const pageSize = ref(10)
const totalOrders = ref(0)

// 订单状态选项
const orderStatuses = ref([
  { value: 'all', label: '全部', icon: 'el-icon-order', count: 0 },
  { value: 'pending_payment', label: '待付款', icon: 'el-icon-money', count: 0 },
  { value: 'pending_shipment', label: '待发货', icon: 'el-icon-box', count: 0 },
  { value: 'pending_receipt', label: '待收货', icon: 'el-icon-s-claim', count: 0 },
  { value: 'completed', label: '已完成', icon: 'el-icon-circle-check', count: 0 },
  { value: 'cancelled', label: '已取消', icon: 'el-icon-circle-close', count: 0 },
  { value: 'refunded', label: '已退款', icon: 'el-icon-refresh-left', count: 0 }
])

// 去购物
const goShopping = () => {
  router.push('/')
}

// 处理状态筛选
const handleStatusChange = (status) => {
  currentStatus.value = status
  currentPage.value = 1 // 重置为第一页
  loadOrders()
}

// 处理查看订单详情
const handleViewDetail = (orderId) => {
  router.push(`/order/detail/${orderId}`)
}

// 处理取消订单
const handleCancelOrder = async (orderId) => {
  ElMessageBox.confirm(
    '确定要取消该订单吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await orderStore.cancelOrder(orderId)
      ElMessage.success('订单已取消')
      loadOrders() // 重新加载订单列表
    } catch (error) {
      ElMessage.error('取消订单失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 处理确认收货
const handleConfirmReceipt = async (orderId) => {
  ElMessageBox.confirm(
    '确认已收到商品吗？确认后订单将完成。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await orderStore.confirmOrder(orderId)
      ElMessage.success('收货成功')
      loadOrders() // 重新加载订单列表
    } catch (error) {
      ElMessage.error('确认收货失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 处理支付订单
const handlePayOrder = (orderId) => {
  // 跳转到支付页面
  router.push(`/pay/order/${orderId}`)
}

// 处理删除订单
const handleDeleteOrder = async (orderId) => {
  ElMessageBox.confirm(
    '确定要删除该订单吗？删除后将无法恢复。',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'danger'
    }
  ).then(async () => {
    try {
      await orderStore.deleteOrder(orderId)
      ElMessage.success('订单已删除')
      loadOrders() // 重新加载订单列表
    } catch (error) {
      ElMessage.error('删除订单失败：' + error.message)
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 处理分页大小变化
const handleSizeChange = (size) => {
  pageSize.value = size
  loadOrders()
}

// 处理当前页变化
const handleCurrentChange = (current) => {
  currentPage.value = current
  loadOrders()
}

// 加载订单列表
const loadOrders = async () => {
  loading.value = true
  try {
    // 检查用户是否登录
    if (!userStore.isLoggedIn) {
      ElMessage.warning('请先登录')
      router.push('/login')
      return
    }
    
    // 模拟API调用，实际项目中替换为真实API
    // const { data, total } = await orderStore.getOrders({
    //   status: currentStatus.value === 'all' ? '' : currentStatus.value,
    //   page: currentPage.value,
    //   pageSize: pageSize.value
    // })
    // orders.value = data
    // totalOrders.value = total
    
    // 模拟订单数据
    const mockOrders = generateMockOrders()
    
    // 根据当前状态筛选订单
    if (currentStatus.value !== 'all') {
      orders.value = mockOrders.filter(order => order.status === currentStatus.value)
    } else {
      orders.value = mockOrders
    }
    
    // 更新订单状态数量
    updateOrderStatusCounts(mockOrders)
    
    // 更新总订单数
    totalOrders.value = orders.value.length
  } catch (error) {
    ElMessage.error('加载订单失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 生成模拟订单数据
const generateMockOrders = () => {
  const mockOrders = [
    {
      id: 'ORD20231125001',
      createTime: '2023-11-25 14:30:25',
      totalAmount: 6999,
      status: 'completed',
      statusText: '已完成',
      items: [
        {
          id: 1,
          productId: 1,
          name: '超级智能手机 Pro Max',
          image: '/product/hot1.png',
          price: 6999,
          quantity: 1,
          specs: { '颜色': '暗夜黑', '内存': '8GB+256GB' }
        }
      ],
      address: {
        name: '张三',
        phone: '138****1234',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detailAddress: '科技园南区8栋101室'
      },
      paymentMethod: 'alipay',
      paymentTime: '2023-11-25 14:35:40',
      shippingTime: '2023-11-26 09:20:30',
      deliveryTime: '2023-11-28 16:45:12'
    },
    {
      id: 'ORD20231124002',
      createTime: '2023-11-24 09:15:10',
      totalAmount: 3498,
      status: 'pending_receipt',
      statusText: '待收货',
      items: [
        {
          id: 2,
          productId: 3,
          name: '智能手表 Series 7',
          image: '/product/hot3.png',
          price: 2199,
          quantity: 1,
          specs: { '颜色': '深空灰', '尺寸': '45mm' }
        },
        {
          id: 3,
          productId: 4,
          name: '无线蓝牙耳机 Pro',
          image: '/product/hot4.png',
          price: 1299,
          quantity: 1,
          specs: { '颜色': '白色' }
        }
      ],
      address: {
        name: '张三',
        phone: '138****1234',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detailAddress: '科技园南区8栋101室'
      },
      paymentMethod: 'wechat',
      paymentTime: '2023-11-24 09:20:35',
      shippingTime: '2023-11-25 10:15:40'
    },
    {
      id: 'ORD20231123003',
      createTime: '2023-11-23 19:45:50',
      totalAmount: 129,
      status: 'pending_payment',
      statusText: '待付款',
      items: [
        {
          id: 4,
          productId: 10,
          name: '无线充电器 15W快充',
          image: '/product/discount2.png',
          price: 129,
          quantity: 1,
          specs: { '颜色': '黑色' }
        }
      ],
      address: {
        name: '张三',
        phone: '138****1234',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detailAddress: '科技园南区8栋101室'
      },
      paymentMethod: 'alipay'
    },
    {
      id: 'ORD20231120004',
      createTime: '2023-11-20 11:30:15',
      totalAmount: 8999,
      status: 'cancelled',
      statusText: '已取消',
      items: [
        {
          id: 5,
          productId: 5,
          name: '全新旗舰手机 Ultra',
          image: '/product/new1.png',
          price: 8999,
          quantity: 1,
          specs: { '颜色': '陶瓷黑', '内存': '12GB+512GB' }
        }
      ],
      address: {
        name: '张三',
        phone: '138****1234',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detailAddress: '科技园南区8栋101室'
      },
      paymentMethod: 'wechat',
      cancelTime: '2023-11-20 12:05:30'
    },
    {
      id: 'ORD20231115005',
      createTime: '2023-11-15 16:20:40',
      totalAmount: 1999,
      status: 'refunded',
      statusText: '已退款',
      items: [
        {
          id: 6,
          productId: 7,
          name: '智能空气净化器',
          image: '/product/new3.png',
          price: 1999,
          quantity: 1,
          specs: { '型号': 'KJ500F-A1' }
        }
      ],
      address: {
        name: '张三',
        phone: '138****1234',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detailAddress: '科技园南区8栋101室'
      },
      paymentMethod: 'alipay',
      paymentTime: '2023-11-15 16:25:55',
      shippingTime: '2023-11-16 08:45:30',
      deliveryTime: '2023-11-18 14:30:15',
      refundTime: '2023-11-20 10:15:40'
    },
    {
      id: 'ORD20231110006',
      createTime: '2023-11-10 08:50:25',
      totalAmount: 3299,
      status: 'pending_shipment',
      statusText: '待发货',
      items: [
        {
          id: 7,
          productId: 6,
          name: '便携投影仪 Mini',
          image: '/product/new2.png',
          price: 3299,
          quantity: 1,
          specs: { '分辨率': '1080P', '亮度': '1000流明' }
        }
      ],
      address: {
        name: '张三',
        phone: '138****1234',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        detailAddress: '科技园南区8栋101室'
      },
      paymentMethod: 'wechat',
      paymentTime: '2023-11-10 08:55:30'
    }
  ]
  
  // 对订单按创建时间倒序排列
  return mockOrders.sort((a, b) => new Date(b.createTime) - new Date(a.createTime))
}

// 更新订单状态数量
const updateOrderStatusCounts = (allOrders) => {
  const statusCountMap = {
    all: 0,
    pending_payment: 0,
    pending_shipment: 0,
    pending_receipt: 0,
    completed: 0,
    cancelled: 0,
    refunded: 0
  }
  
  // 统计各状态订单数量
  allOrders.forEach(order => {
    statusCountMap.all++
    if (statusCountMap.hasOwnProperty(order.status)) {
      statusCountMap[order.status]++
    }
  })
  
  // 更新订单状态选项的数量
  orderStatuses.value.forEach(status => {
    status.count = statusCountMap[status.value] || 0
  })
}

// 组件挂载时加载数据
onMounted(() => {
  loadOrders()
})
</script>

<style scoped>
.order-list-container {
  width: 100%;
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
  box-sizing: border-box;
}

/* 面包屑导航 */
.breadcrumb-section {
  margin: 20px 0;
}

/* 页面标题 */
.page-header {
  margin-bottom: 30px;
}

.page-title {
  font-size: $font-size-xxl;
  color: $text-color;
  font-weight: bold;
  margin: 0 0 10px 0;
}

.page-subtitle {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  margin: 0;
}

/* 订单状态筛选 */
.order-status-filter {
  display: flex;
  gap: 20px;
  padding: 16px 0;
  margin-bottom: 20px;
  border-bottom: 2px solid $border-color;
  overflow-x: auto;
}

.status-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  border-radius: $border-radius-base;
  cursor: pointer;
  white-space: nowrap;
  transition: all 0.3s;
}

.status-item:hover {
  background-color: $hover-color;
}

.status-item.active {
  background-color: $primary-color;
  color: #fff;
}

.status-icon {
  font-size: $font-size-base;
}

.status-text {
  font-size: $font-size-base;
}

.status-count {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  min-width: 16px;
  height: 16px;
  padding: 0 4px;
  background-color: $danger-color;
  color: #fff;
  font-size: $font-size-xs;
  border-radius: 8px;
  line-height: 1;
}

.status-item.active .status-count {
  background-color: #fff;
  color: $danger-color;
}

/* 订单列表内容 */
.order-list-content {
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
  padding: 0;
}

/* 订单为空 */
.empty-orders {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 500px;
  padding: 40px;
}

.empty-icon {
  font-size: 100px;
  color: $text-color-placeholder;
  margin-bottom: 20px;
}

.empty-text {
  font-size: $font-size-base;
  color: $text-color-secondary;
  margin-bottom: 20px;
}

.go-shopping-btn {
  padding: 10px 30px;
  font-size: $font-size-base;
}

/* 订单列表 */
.orders-list {
  /* 由OrderItem组件填充 */
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  padding: 20px;
  border-top: 1px solid $border-color;
  background-color: #fff;
}

/* 加载状态 */
.loading-container {
  min-height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: $border-radius-base;
  box-shadow: $shadow-base;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  /* 保持现有样式 */
}

@media (max-width: 992px) {
  .order-status-filter {
    gap: 15px;
  }
  
  .status-item {
    padding: 6px 12px;
  }
  
  .status-text {
    font-size: $font-size-sm;
  }
}

@media (max-width: 768px) {
  .order-list-container {
    padding: 0 10px;
  }
  
  .page-header {
    margin-bottom: 20px;
  }
  
  .page-title {
    font-size: $font-size-xl;
  }
  
  .order-status-filter {
    gap: 10px;
    padding: 12px 0;
  }
  
  .status-item {
    padding: 4px 8px;
  }
  
  .status-text {
    font-size: $font-size-xs;
  }
  
  .pagination-section {
    padding: 15px;
    justify-content: center;
  }
  
  .el-pagination {
    font-size: $font-size-xs;
  }
}

@media (max-width: 480px) {
  .empty-orders {
    padding: 20px;
  }
  
  .empty-icon {
    font-size: 80px;
  }
  
  .order-status-filter {
    gap: 5px;
  }
  
  .status-item {
    padding: 3px 6px;
    gap: 4px;
  }
}
</style>